{
  "name": "Case 55: Clinical Trial Patient Eligibility Screener",
  "nodes": [
    {
      "parameters": {
        "pollTimes": {
          "item": [
            {
              "mode": "everyMinute"
            }
          ]
        },
        "triggerOn": "specificFolder",
        "folderToWatch": {
          "__rl": true,
          "value": "1kupq6nstCXh9VLIFa9XWNLLJOFcTuMxp",
          "mode": "list",
          "cachedResultName": "Case 55 - Clinical Trial Patient Folder",
          "cachedResultUrl": "https://drive.google.com/drive/folders/1kupq6nstCXh9VLIFa9XWNLLJOFcTuMxp"
        },
        "event": "fileCreated",
        "options": {}
      },
      "id": "0a73208d-e895-4c4e-8372-4c83e0a4d52b",
      "name": "Monitor Patient Records Folder",
      "type": "n8n-nodes-base.googleDriveTrigger",
      "typeVersion": 1,
      "position": [
        -1280,
        0
      ],
      "credentials": {
        "googleDriveOAuth2Api": {
          "id": "Cf6MNES8JrQntp3r",
          "name": "Google Drive account"
        }
      }
    },
    {
      "parameters": {
        "operation": "download",
        "fileId": {
          "__rl": true,
          "value": "={{ $json.id }}",
          "mode": "id"
        },
        "options": {}
      },
      "id": "e5c44a81-5d07-4484-85e0-17a1090a7178",
      "name": "Download Patient Record",
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        -1072,
        0
      ],
      "credentials": {
        "googleDriveOAuth2Api": {
          "id": "Cf6MNES8JrQntp3r",
          "name": "Google Drive account"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.cloud.llamaindex.ai/api/v1/parsing/upload",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer llx-7BWYrvPwfUhgdXbZMtaNCsr2O0h7JH4dkHjHisxcvq46bkIj"
            }
          ]
        },
        "sendBody": true,
        "contentType": "multipart-form-data",
        "bodyParameters": {
          "parameters": [
            {
              "parameterType": "formBinaryData",
              "name": "file",
              "inputDataFieldName": "data"
            }
          ]
        },
        "options": {}
      },
      "id": "10b069e1-499f-44a2-a1b7-08f60e3ecb88",
      "name": "Upload to Parser",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        -880,
        0
      ]
    },
    {
      "parameters": {
        "amount": 20
      },
      "id": "2cde0b51-bd98-4b60-82e4-43311a140f84",
      "name": "Wait for Parsing",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        -704,
        0
      ],
      "webhookId": "cec86aeb-8259-4b83-8ef6-cc1415ec86d1"
    },
    {
      "parameters": {
        "url": "=https://api.cloud.llamaindex.ai/api/v1/parsing/job/{{ $node[\"Upload to Parser\"].json[\"id\"] }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer llx-7BWYrvPwfUhgdXbZMtaNCsr2O0h7JH4dkHjHisxcvq46bkIj"
            }
          ]
        },
        "options": {}
      },
      "id": "620298da-105b-4a89-99ca-10088174a48e",
      "name": "Check Parsing Status",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        -480,
        0
      ]
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "conditions": [
                  {
                    "leftValue": "={{ $json.status }}",
                    "rightValue": "SUCCESS",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ]
              },
              "renameOutput": true,
              "outputKey": "SUCCESS"
            },
            {
              "conditions": {
                "conditions": [
                  {
                    "leftValue": "={{ $json.status }}",
                    "rightValue": "PENDING",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ]
              },
              "renameOutput": true,
              "outputKey": "PENDING"
            }
          ]
        },
        "options": {}
      },
      "id": "bb734269-0b14-422a-ba71-5c8d72593a61",
      "name": "Route Based on Status",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.3,
      "position": [
        -256,
        0
      ]
    },
    {
      "parameters": {
        "url": "=https://api.cloud.llamaindex.ai/api/v1/parsing/job/{{ $node[\"Upload to Parser\"].json[\"id\"] }}/result/markdown",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer llx-7BWYrvPwfUhgdXbZMtaNCsr2O0h7JH4dkHjHisxcvq46bkIj"
            }
          ]
        },
        "options": {}
      },
      "id": "01458efb-32b6-4d37-849b-dc729c1b7b28",
      "name": "Extract Parsed Content",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        -16,
        -96
      ]
    },
    {
      "parameters": {
        "text": "={{ $json.markdown }}",
        "attributes": {
          "attributes": [
            {
              "name": "Patient_ID",
              "description": "Patient medical record number or ID"
            },
            {
              "name": "Patient_Name",
              "description": "Patient full name"
            },
            {
              "name": "Age",
              "description": "Patient age in years"
            },
            {
              "name": "Gender",
              "description": "Male or Female"
            },
            {
              "name": "Primary_Diagnosis",
              "description": "Main diagnosis or disease"
            },
            {
              "name": "Secondary_Diagnoses",
              "description": "Additional diagnoses or comorbidities"
            },
            {
              "name": "Current_Medications",
              "description": "List of current medications patient is taking"
            },
            {
              "name": "Previous_Treatments",
              "description": "Past treatments or therapies received"
            },
            {
              "name": "Lab_Values",
              "description": "Recent laboratory test results (HbA1c, creatinine, liver enzymes, etc)"
            },
            {
              "name": "ECOG_Performance_Status",
              "description": "ECOG performance status score (0-4)"
            },
            {
              "name": "Smoking_Status",
              "description": "Current smoker, former smoker, or never smoked"
            },
            {
              "name": "Pregnancy_Status",
              "description": "For females - pregnant, not pregnant, or not applicable"
            },
            {
              "name": "Blood_Pressure",
              "description": "Blood pressure reading in mmHg (e.g., 138/82)"
            }
          ]
        },
        "options": {}
      },
      "id": "70efa7ae-cef0-41e2-ad2b-43894812c557",
      "name": "AI Data Extractor",
      "type": "@n8n/n8n-nodes-langchain.informationExtractor",
      "typeVersion": 1.2,
      "position": [
        192,
        -96
      ]
    },
    {
      "parameters": {
        "jsCode": "const patientData = $input.first().json.output;\n\n// ROBUST NUMBER EXTRACTION\nconst extractNumber = (str) => {\n  if (!str) return 0;\n  const cleaned = str.toString().replace(/[^\\d.-]/g, '');\n  const num = parseFloat(cleaned);\n  return isNaN(num) ? 0 : num;\n};\n\n// EMBEDDED CLINICAL TRIAL DATABASE\nconst clinicalTrials = {\n  \"TRIAL-DM-2025-01\": {\n    trial_name: \"GLP-1 Agonist for Type 2 Diabetes\",\n    phase: \"Phase 3\",\n    condition: \"Type 2 Diabetes Mellitus\",\n    sponsor: \"NovoPharm Research\",\n    inclusion_criteria: {\n      age_min: 18,\n      age_max: 75,\n      diagnoses_required: [\"type 2 diabetes\", \"diabetes mellitus type 2\", \"t2dm\"],\n      hba1c_min: 7.0,\n      hba1c_max: 11.0,\n      ecog_max: 2\n    },\n    exclusion_criteria: {\n      diagnoses_excluded: [\"type 1 diabetes\", \"diabetic ketoacidosis\", \"severe renal impairment\"],\n      medications_excluded: [\"insulin\", \"sglt2 inhibitor\"],\n      pregnancy: true,\n      smoking_excluded: false\n    },\n    enrollment_target: 500,\n    current_enrolled: 342,\n    priority_score_base: 85\n  },\n  \"TRIAL-HTN-2025-02\": {\n    trial_name: \"Novel ARB for Resistant Hypertension\",\n    phase: \"Phase 2\",\n    condition: \"Resistant Hypertension\",\n    sponsor: \"CardioMed Inc\",\n    inclusion_criteria: {\n      age_min: 35,\n      age_max: 70,\n      diagnoses_required: [\"hypertension\", \"high blood pressure\", \"resistant hypertension\"],\n      systolic_bp_min: 140,\n      ecog_max: 1\n    },\n    exclusion_criteria: {\n      diagnoses_excluded: [\"heart failure\", \"myocardial infarction\", \"stroke\"],\n      medications_excluded: [\"ace inhibitor and arb combination\"],\n      pregnancy: true,\n      creatinine_max: 2.0\n    },\n    enrollment_target: 200,\n    current_enrolled: 145,\n    priority_score_base: 75\n  },\n  \"TRIAL-COPD-2025-03\": {\n    trial_name: \"Dual Bronchodilator for Severe COPD\",\n    phase: \"Phase 3\",\n    condition: \"Chronic Obstructive Pulmonary Disease\",\n    sponsor: \"RespiraTech\",\n    inclusion_criteria: {\n      age_min: 40,\n      age_max: 80,\n      diagnoses_required: [\"copd\", \"chronic obstructive pulmonary disease\", \"emphysema\"],\n      fev1_max: 50,\n      smoking_history_required: true,\n      ecog_max: 2\n    },\n    exclusion_criteria: {\n      diagnoses_excluded: [\"asthma\", \"lung cancer\", \"active tuberculosis\"],\n      medications_excluded: [],\n      pregnancy: true,\n      current_smoker_excluded: false\n    },\n    enrollment_target: 350,\n    current_enrolled: 287,\n    priority_score_base: 80\n  },\n  \"TRIAL-CKD-2025-04\": {\n    trial_name: \"SGLT2 Inhibitor for CKD Progression\",\n    phase: \"Phase 3\",\n    condition: \"Chronic Kidney Disease\",\n    sponsor: \"NephroGen Labs\",\n    inclusion_criteria: {\n      age_min: 18,\n      age_max: 85,\n      diagnoses_required: [\"chronic kidney disease\", \"ckd\", \"renal impairment\"],\n      egfr_min: 25,\n      egfr_max: 75,\n      ecog_max: 3\n    },\n    exclusion_criteria: {\n      diagnoses_excluded: [\"kidney transplant\", \"dialysis\"],\n      medications_excluded: [],\n      pregnancy: true,\n      potassium_max: 5.5\n    },\n    enrollment_target: 400,\n    current_enrolled: 298,\n    priority_score_base: 90\n  },\n  \"TRIAL-CA-2025-05\": {\n    trial_name: \"Immunotherapy for Advanced NSCLC\",\n    phase: \"Phase 2\",\n    condition: \"Non-Small Cell Lung Cancer\",\n    sponsor: \"OncoImmune Research\",\n    inclusion_criteria: {\n      age_min: 18,\n      age_max: 999,\n      diagnoses_required: [\"non-small cell lung cancer\", \"nsclc\", \"lung cancer\"],\n      ecog_max: 2,\n      pd_l1_min: 50\n    },\n    exclusion_criteria: {\n      diagnoses_excluded: [\"small cell lung cancer\", \"autoimmune disease\", \"organ transplant\"],\n      medications_excluded: [\"immunosuppressant\", \"systemic corticosteroids\"],\n      pregnancy: true,\n      previous_immunotherapy: true\n    },\n    enrollment_target: 150,\n    current_enrolled: 89,\n    priority_score_base: 95\n  }\n};\n\n// DRUG INTERACTION DATABASE\nconst drugInteractions = {\n  \"warfarin\": [\"nsaid\", \"aspirin\", \"antiplatelet\"],\n  \"methotrexate\": [\"nsaid\", \"trimethoprim\"],\n  \"digoxin\": [\"amiodarone\", \"verapamil\"],\n  \"lithium\": [\"ace inhibitor\", \"arb\", \"nsaid\"],\n  \"immunosuppressant\": [\"live vaccine\"]\n};\n\n// Extract patient data\nconst patientID = patientData.Patient_ID || 'UNKNOWN';\nconst patientName = patientData.Patient_Name || 'Unknown';\nconst age = extractNumber(patientData.Age);\nconst gender = (patientData.Gender || 'Unknown').toLowerCase();\nconst primaryDiagnosis = (patientData.Primary_Diagnosis || '').toLowerCase();\nconst secondaryDiagnoses = (patientData.Secondary_Diagnoses || '').toLowerCase();\nconst allDiagnoses = primaryDiagnosis + ' ' + secondaryDiagnoses;\nconst currentMedications = (patientData.Current_Medications || '').toLowerCase();\nconst previousTreatments = (patientData.Previous_Treatments || '').toLowerCase();\nconst labValues = patientData.Lab_Values || '';\nconst ecogStatus = extractNumber(patientData.ECOG_Performance_Status);\nconst smokingStatus = (patientData.Smoking_Status || '').toLowerCase();\nconst pregnancyStatus = (patientData.Pregnancy_Status || '').toLowerCase();\n\n// Parse lab values\nconst parseLabValue = (labStr, keyword) => {\n  const regex = new RegExp(keyword + '[:\\\\s]+([\\\\d.]+)', 'i');\n  const match = labStr.match(regex);\n  return match ? parseFloat(match[1]) : null;\n};\n\nconst hba1c = parseLabValue(labValues, 'hba1c');\nconst creatinine = parseLabValue(labValues, 'creatinine');\nconst egfr = parseLabValue(labValues, 'egfr');\nconst potassium = parseLabValue(labValues, 'potassium');\nconst fev1 = parseLabValue(labValues, 'fev1');\nconst pdl1 = parseLabValue(labValues, 'pd-l1');\nconst systolicBP = parseLabValue(labValues, 'systolic') || parseLabValue(patientData.Blood_Pressure || '', 'systolic') || extractNumber((patientData.Blood_Pressure || '').split('/')[0]);\n\n// INTELLIGENCE: Match patient against all trials\nconst trialMatches = [];\n\nfor (const [trialID, trial] of Object.entries(clinicalTrials)) {\n  const inclusion = trial.inclusion_criteria;\n  const exclusion = trial.exclusion_criteria;\n  \n  let eligible = true;\n  const inclusionMet = [];\n  const inclusionFailed = [];\n  const exclusionViolations = [];\n  let matchScore = 0;\n  \n  // Check inclusion criteria\n  \n  // Age check\n  if (age < inclusion.age_min || age > inclusion.age_max) {\n    eligible = false;\n    inclusionFailed.push(`Age ${age} outside range ${inclusion.age_min}-${inclusion.age_max}`);\n  } else {\n    inclusionMet.push(`Age ${age} within range`);\n    matchScore += 20;\n  }\n  \n  // Diagnosis check\n  const hasDiagnosis = inclusion.diagnoses_required.some(dx => allDiagnoses.includes(dx));\n  if (!hasDiagnosis) {\n    eligible = false;\n    inclusionFailed.push(`Required diagnosis not found: ${inclusion.diagnoses_required.join(' OR ')}`);\n  } else {\n    inclusionMet.push('Required diagnosis present');\n    matchScore += 30;\n  }\n  \n  // ECOG check\n  if (ecogStatus > inclusion.ecog_max) {\n    eligible = false;\n    inclusionFailed.push(`ECOG ${ecogStatus} exceeds max ${inclusion.ecog_max}`);\n  } else if (ecogStatus > 0) {\n    inclusionMet.push(`ECOG ${ecogStatus} acceptable`);\n    matchScore += 10;\n  }\n  \n  // Lab value checks (trial-specific)\n  if (inclusion.hba1c_min && hba1c) {\n    if (hba1c < inclusion.hba1c_min || hba1c > inclusion.hba1c_max) {\n      eligible = false;\n      inclusionFailed.push(`HbA1c ${hba1c}% outside range ${inclusion.hba1c_min}-${inclusion.hba1c_max}%`);\n    } else {\n      inclusionMet.push(`HbA1c ${hba1c}% in range`);\n      matchScore += 15;\n    }\n  }\n  \n  if (inclusion.egfr_min && egfr) {\n    if (egfr < inclusion.egfr_min || egfr > inclusion.egfr_max) {\n      eligible = false;\n      inclusionFailed.push(`eGFR ${egfr} outside range ${inclusion.egfr_min}-${inclusion.egfr_max}`);\n    } else {\n      inclusionMet.push(`eGFR ${egfr} in range`);\n      matchScore += 15;\n    }\n  }\n  \n  if (inclusion.fev1_max && fev1) {\n    if (fev1 > inclusion.fev1_max) {\n      eligible = false;\n      inclusionFailed.push(`FEV1 ${fev1}% exceeds max ${inclusion.fev1_max}%`);\n    } else {\n      inclusionMet.push(`FEV1 ${fev1}% meets criteria`);\n      matchScore += 15;\n    }\n  }\n  \n  if (inclusion.pd_l1_min && pdl1) {\n    if (pdl1 < inclusion.pd_l1_min) {\n      eligible = false;\n      inclusionFailed.push(`PD-L1 ${pdl1}% below minimum ${inclusion.pd_l1_min}%`);\n    } else {\n      inclusionMet.push(`PD-L1 ${pdl1}% meets threshold`);\n      matchScore += 15;\n    }\n  }\n  \n  if (inclusion.systolic_bp_min && systolicBP) {\n    if (systolicBP < inclusion.systolic_bp_min) {\n      eligible = false;\n      inclusionFailed.push(`Systolic BP ${systolicBP} below minimum ${inclusion.systolic_bp_min}`);\n    } else {\n      inclusionMet.push(`Systolic BP ${systolicBP} meets criteria`);\n      matchScore += 10;\n    }\n  }\n  \n  if (inclusion.smoking_history_required && !smokingStatus.includes('former') && !smokingStatus.includes('current')) {\n    eligible = false;\n    inclusionFailed.push('Smoking history required');\n  }\n  \n  // Check exclusion criteria\n  \n  // Excluded diagnoses\n  for (const excludedDx of exclusion.diagnoses_excluded) {\n    if (allDiagnoses.includes(excludedDx)) {\n      eligible = false;\n      exclusionViolations.push(`Excluded diagnosis present: ${excludedDx}`);\n    }\n  }\n  \n  // Excluded medications\n  for (const excludedMed of exclusion.medications_excluded) {\n    if (currentMedications.includes(excludedMed)) {\n      eligible = false;\n      exclusionViolations.push(`Excluded medication: ${excludedMed}`);\n    }\n  }\n  \n  // Pregnancy check\n  if (exclusion.pregnancy && gender === 'female' && pregnancyStatus.includes('pregnant')) {\n    eligible = false;\n    exclusionViolations.push('Pregnancy excluded');\n  }\n  \n  // Lab exclusions\n  if (exclusion.creatinine_max && creatinine && creatinine > exclusion.creatinine_max) {\n    eligible = false;\n    exclusionViolations.push(`Creatinine ${creatinine} exceeds max ${exclusion.creatinine_max}`);\n  }\n  \n  if (exclusion.potassium_max && potassium && potassium > exclusion.potassium_max) {\n    eligible = false;\n    exclusionViolations.push(`Potassium ${potassium} exceeds max ${exclusion.potassium_max}`);\n  }\n  \n  // Previous treatment exclusions\n  if (exclusion.previous_immunotherapy && previousTreatments.includes('immunotherapy')) {\n    eligible = false;\n    exclusionViolations.push('Prior immunotherapy excluded');\n  }\n  \n  if (exclusion.current_smoker_excluded && smokingStatus.includes('current')) {\n    eligible = false;\n    exclusionViolations.push('Current smoking excluded');\n  }\n  \n  // Calculate enrollment probability\n  const spotsRemaining = trial.enrollment_target - trial.current_enrolled;\n  const urgencyBonus = spotsRemaining < 50 ? 10 : 0;\n  const finalScore = eligible ? Math.min(trial.priority_score_base + matchScore + urgencyBonus, 100) : 0;\n  \n  // Determine enrollment priority\n  let enrollmentPriority = 'Not Eligible';\n  if (eligible) {\n    if (finalScore >= 90) enrollmentPriority = 'High Priority';\n    else if (finalScore >= 75) enrollmentPriority = 'Medium Priority';\n    else enrollmentPriority = 'Low Priority';\n  }\n  \n  trialMatches.push({\n    Trial_ID: trialID,\n    Trial_Name: trial.trial_name,\n    Phase: trial.phase,\n    Condition: trial.condition,\n    Sponsor: trial.sponsor,\n    Eligibility_Status: eligible ? '✅ ELIGIBLE' : '❌ NOT ELIGIBLE',\n    Enrollment_Probability: `${finalScore}%`,\n    Enrollment_Priority: enrollmentPriority,\n    Inclusion_Criteria_Met: inclusionMet.join('; ') || 'None',\n    Inclusion_Criteria_Failed: inclusionFailed.join('; ') || 'None',\n    Exclusion_Violations: exclusionViolations.join('; ') || 'None',\n    Spots_Remaining: spotsRemaining,\n    Total_Enrolled: trial.current_enrolled,\n    Target_Enrollment: trial.enrollment_target\n  });\n}\n\n// Sort by enrollment probability (descending)\ntrialMatches.sort((a, b) => {\n  const probA = parseInt(a.Enrollment_Probability);\n  const probB = parseInt(b.Enrollment_Probability);\n  return probB - probA;\n});\n\n// Create output for each trial match\nconst outputItems = trialMatches.map(trial => ({\n  json: {\n    Patient_ID: patientID,\n    Patient_Name: patientName,\n    Age: age.toString(),\n    Gender: patientData.Gender || 'Unknown',\n    Primary_Diagnosis: patientData.Primary_Diagnosis || 'Unknown',\n    ECOG_Status: ecogStatus.toString(),\n    ...trial,\n    Processing_Timestamp: new Date().toISOString()\n  }\n}));\n\nreturn outputItems;"
      },
      "id": "ee2bbbc3-907b-4b7f-a489-feb1967a2c0b",
      "name": "Trial Eligibility Matcher",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        496,
        -96
      ]
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "1BQqh115v1mdgGYIqXIJj8Kc0nf28EtTJgyex9rGTyYc",
          "mode": "list",
          "cachedResultName": "Case 55 - Clinical Trial Patient Log",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1BQqh115v1mdgGYIqXIJj8Kc0nf28EtTJgyex9rGTyYc/edit?usp=drivesdk"
        },
        "sheetName": {
          "__rl": true,
          "value": "gid=0",
          "mode": "list",
          "cachedResultName": "Sheet1",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1BQqh115v1mdgGYIqXIJj8Kc0nf28EtTJgyex9rGTyYc/edit#gid=0"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {},
          "matchingColumns": [],
          "schema": [
            {
              "id": "Patient_ID",
              "displayName": "Patient_ID",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Patient_Name",
              "displayName": "Patient_Name",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Age",
              "displayName": "Age",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Gender",
              "displayName": "Gender",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Primary_Diagnosis",
              "displayName": "Primary_Diagnosis",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "ECOG_Status",
              "displayName": "ECOG_Status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Trial_ID",
              "displayName": "Trial_ID",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Trial_Name",
              "displayName": "Trial_Name",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Phase",
              "displayName": "Phase",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Condition",
              "displayName": "Condition",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Sponsor",
              "displayName": "Sponsor",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Eligibility_Status",
              "displayName": "Eligibility_Status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Enrollment_Probability",
              "displayName": "Enrollment_Probability",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Enrollment_Priority",
              "displayName": "Enrollment_Priority",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Inclusion_Criteria_Met",
              "displayName": "Inclusion_Criteria_Met",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Inclusion_Criteria_Failed",
              "displayName": "Inclusion_Criteria_Failed",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Exclusion_Violations",
              "displayName": "Exclusion_Violations",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Spots_Remaining",
              "displayName": "Spots_Remaining",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Total_Enrolled",
              "displayName": "Total_Enrolled",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Target_Enrollment",
              "displayName": "Target_Enrollment",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Processing_Timestamp",
              "displayName": "Processing_Timestamp",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "id": "7d7e654a-cdb5-4c7c-a482-9d6f8b81729e",
      "name": "Log to Google Sheets",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        688,
        -96
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "LOs2dbk9lby0NfDM",
          "name": "Google Sheets account"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "const allMatches = $input.all();\nconsole.log('Total items received:', allMatches.length);\nconsole.log('First item:', JSON.stringify(allMatches[0]?.json, null, 2));\n\nconst patientID = allMatches[0]?.json.Patient_ID || 'Unknown';\nconst patientName = allMatches[0]?.json.Patient_Name || 'Unknown';\nconst age = allMatches[0]?.json.Age || 'Unknown';\nconst primaryDiagnosis = allMatches[0]?.json.Primary_Diagnosis || 'Unknown';\n\nconst eligibleTrials = allMatches.filter(m => m.json?.Eligibility_Status?.includes('✅'));\nconst notEligibleTrials = allMatches.filter(m => m.json?.Eligibility_Status?.includes('❌'));\n\nconst highPriority = eligibleTrials.filter(m => m.json.Enrollment_Priority === 'High Priority');\nconst mediumPriority = eligibleTrials.filter(m => m.json.Enrollment_Priority === 'Medium Priority');\n\nconst emailSubject = eligibleTrials.length > 0 \n  ? `Patient Match Found: ${patientName} - ${eligibleTrials.length} Eligible Trial(s)` \n  : `No Trial Matches: ${patientName}`;\n\nlet emailBody = `Dear Research Coordinator,\n\nA patient record has been screened against active clinical trials.\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n👤 PATIENT INFORMATION\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\nPatient ID: ${patientID}\nPatient Name: ${patientName}\nAge: ${age} years\nPrimary Diagnosis: ${primaryDiagnosis}\nECOG Performance Status: ${allMatches[0]?.json.ECOG_Status || 'Not recorded'}\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n📊 SCREENING SUMMARY\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\nTotal Trials Screened: ${allMatches.length}\n✅ Eligible Trials: ${eligibleTrials.length}\n❌ Ineligible Trials: ${notEligibleTrials.length}\n\n`;\n\nif (eligibleTrials.length > 0) {\n  emailBody += `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n✅ ELIGIBLE TRIALS (Ranked by Priority)\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n`;\n  \n  eligibleTrials.forEach((trial, index) => {\n    const priorityEmoji = trial.json.Enrollment_Priority === 'High Priority' ? '🔥' : \n                          trial.json.Enrollment_Priority === 'Medium Priority' ? '⚡' : '📋';\n    \n    emailBody += `${index + 1}. ${priorityEmoji} ${trial.json.Trial_Name}\n`;\n    emailBody += `   Trial ID: ${trial.json.Trial_ID}\n`;\n    emailBody += `   Phase: ${trial.json.Phase}\n`;\n    emailBody += `   Sponsor: ${trial.json.Sponsor}\n`;\n    emailBody += `   Enrollment Probability: ${trial.json.Enrollment_Probability}\n`;\n    emailBody += `   Priority: ${trial.json.Enrollment_Priority}\n`;\n    emailBody += `   Spots Remaining: ${trial.json.Spots_Remaining}/${trial.json.Target_Enrollment}\n`;\n    emailBody += `   ✓ Criteria Met: ${trial.json.Inclusion_Criteria_Met}\n`;\n    emailBody += `\\n`;\n  });\n}\n\nif (notEligibleTrials.length > 0) {\n  emailBody += `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n❌ INELIGIBLE TRIALS\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n`;\n  \n  notEligibleTrials.slice(0, 3).forEach((trial, index) => {\n    emailBody += `${index + 1}. ${trial.json.Trial_Name}\n`;\n    emailBody += `   Reason: ${trial.json.Inclusion_Criteria_Failed || trial.json.Exclusion_Violations}\n`;\n    emailBody += `\\n`;\n  });\n  \n  if (notEligibleTrials.length > 3) {\n    emailBody += `   ... and ${notEligibleTrials.length - 3} more (see detailed report)\n\\n`;\n  }\n}\n\nif (eligibleTrials.length > 0) {\n  emailBody += `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n🎯 RECOMMENDED NEXT STEPS\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`;\n  \n  if (highPriority.length > 0) {\n    emailBody += `1. URGENT: Contact patient immediately for ${highPriority[0].json.Trial_Name}\n`;\n    emailBody += `2. Schedule screening visit within 3-5 days\n`;\n    emailBody += `3. Prepare informed consent documents\n`;\n    emailBody += `4. Coordinate with principal investigator\n`;\n  } else {\n    emailBody += `1. Review eligible trials with patient\n`;\n    emailBody += `2. Discuss trial benefits and requirements\n`;\n    emailBody += `3. Schedule screening visit if patient interested\n`;\n    emailBody += `4. Document patient decision\n`;\n  }\n} else {\n  emailBody += `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n📋 NEXT STEPS\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\nNo eligible trials at this time. Patient record will be re-screened when new trials open.\nConsider referring to standard of care treatment protocols.\n`;\n}\n\nemailBody += `\\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\nDetailed screening results logged to Clinical Trial Database.\nProcessed: ${new Date().toISOString()}\n\nThis is an automated screening from the Clinical Trial Eligibility System.\n\nBest regards,\nClinical Trial Screening System`;\n\nreturn {\n  json: {\n    email_subject: emailSubject,\n    email_body: emailBody,\n    recipient_email: 'research.coordinator@hospital.com',\n    cc_email: eligibleTrials.length > 0 ? 'principal.investigator@hospital.com' : '',\n    patient_id: patientID,\n    patient_name: patientName,\n    eligible_trials_count: eligibleTrials.length,\n    high_priority_count: highPriority.length\n  }\n};"
      },
      "id": "e87b3fe0-3ddc-48a9-a3f2-904e9021540a",
      "name": "Generate Email Summary",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        928,
        -96
      ]
    },
    {
      "parameters": {
        "sendTo": "={{ $json.recipient_email }}",
        "subject": "={{ $json.email_subject }}",
        "emailType": "text",
        "message": "={{ $json.email_body }}",
        "options": {}
      },
      "id": "b5d9e735-415f-4b80-9a49-e6d271ebfad2",
      "name": "Send Email via Gmail",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        1152,
        -96
      ],
      "webhookId": "4eda12c9-65bc-4426-bc29-0c710fb0731b",
      "credentials": {
        "gmailOAuth2": {
          "id": "cyqCGWcggZNMcSOv",
          "name": "Gmail account"
        }
      }
    },
    {
      "parameters": {
        "model": {
          "__rl": true,
          "value": "gpt-4o-mini",
          "mode": "list"
        },
        "builtInTools": {},
        "options": {}
      },
      "id": "ae9ca475-c31f-4320-b77a-871f71fd359e",
      "name": "OpenAI GPT-4o Mini",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.3,
      "position": [
        192,
        128
      ],
      "credentials": {
        "openAiApi": {
          "id": "ICwxUBbatsF2sDvy",
          "name": "OpenAi account"
        }
      }
    }
  ],
  "pinData": {},
  "connections": {
    "Monitor Patient Records Folder": {
      "main": [
        [
          {
            "node": "Download Patient Record",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Download Patient Record": {
      "main": [
        [
          {
            "node": "Upload to Parser",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Upload to Parser": {
      "main": [
        [
          {
            "node": "Wait for Parsing",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wait for Parsing": {
      "main": [
        [
          {
            "node": "Check Parsing Status",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Parsing Status": {
      "main": [
        [
          {
            "node": "Route Based on Status",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Route Based on Status": {
      "main": [
        [
          {
            "node": "Extract Parsed Content",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Wait for Parsing",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract Parsed Content": {
      "main": [
        [
          {
            "node": "AI Data Extractor",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Data Extractor": {
      "main": [
        [
          {
            "node": "Trial Eligibility Matcher",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Trial Eligibility Matcher": {
      "main": [
        [
          {
            "node": "Log to Google Sheets",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log to Google Sheets": {
      "main": [
        [
          {
            "node": "Generate Email Summary",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate Email Summary": {
      "main": [
        [
          {
            "node": "Send Email via Gmail",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI GPT-4o Mini": {
      "ai_languageModel": [
        [
          {
            "node": "AI Data Extractor",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "84cd5334-edf3-4ded-8a74-a6dac4b7d842",
  "meta": {
    "templateCredsSetupCompleted": true,
    "instanceId": "3a43da28588548e21903e71cf1dc3ddd65c24bf0c62e7e4b77542ffe87ad79c6"
  },
  "id": "XWlI30uYRepggymC",
  "tags": []
}